<template>
  <div class="my-song">
    <div class="song-header">
      <h1>我的创作</h1>
      <el-button type="primary" @click="showUploadDialog(false)">上传音乐</el-button>
    </div>

    <!-- 音乐列表 -->
    <div class="song-list" v-if="songList.length > 0">
      <el-table :data="songList" stripe>
        <el-table-column prop="name" label="音乐名称"></el-table-column>
        <el-table-column label="封面">
          <template slot-scope="scope">
            <img :src="attachImageUrl(scope.row.pic)" class="song-pic">
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button type="text" @click="playSong(scope.row)">播放</el-button>
            <el-button type="text" @click="editSong(scope.row)">编辑</el-button>
            <el-button type="text" @click="deleteSong(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-else class="empty-tip">
      暂无创作,快去上传吧~
    </div>

    <!-- 上传对话框 -->
    <el-dialog :title="isEdit ? '编辑音乐' : '上传音乐'" :visible.sync="uploadDialogVisible" @closed="handleDialogClose">
      <el-form :model="songForm" label-width="80px">
        <el-form-item label="音乐名称">
          <el-input v-model="songForm.name"></el-input>
        </el-form-item>
        <el-form-item label="音乐文件">
          <el-upload
              ref="songUpload"
              class="upload-demo"
              :action="uploadUrl + '/user-song/upload/song'"
              :headers="headers"
              :on-success="handleSongSuccess"
              :before-upload="beforeSongUpload">
            <el-button size="small" type="primary">选择文件</el-button>
            <div slot="tip" class="el-upload__tip" v-if="songForm.url">
              当前文件: {{getFileName(songForm.url)}}
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="封面">
          <el-upload
              ref="picUpload"
              class="avatar-uploader"
              :action="uploadUrl + '/user-song/upload/pic'"
              :headers="headers"
              :show-file-list="false"
              :on-success="handlePicSuccess"
              :before-upload="beforePicUpload">
            <img v-if="songForm.pic" :src="attachImageUrl(songForm.pic)" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="歌词">
          <el-input type="textarea" v-model="songForm.lyric"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUpload">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getUserSongs, addUserSong, deleteUserSong, updateUserSong } from '../api/index'

export default {
  name: 'MySong',
  data() {
    return {
      songList: [],
      uploadDialogVisible: false,
      songForm: {
        name: '',
        url: '',
        pic: '',
        lyric: ''
      },
      uploadUrl: 'http://localhost:8888',
      headers: {},
      isEdit: false,
      editId: null,
      defaultSongForm: {
        name: '',
        url: '',
        pic: '',
        lyric: ''
      }
    }
  },
  computed: {
    ...mapGetters([
      'userId'
    ])
  },
  created() {
    this.checkLogin()
    this.getSongList()
    this.headers = {
      'Access-Control-Allow-Origin': '*'
    }
  },
  methods: {
    // 检查登录状态
    checkLogin() {
      if (!this.userId) {
        this.$message.error('请先登录')
        this.$router.push({
          path: '/login-in',
          query: { redirect: '/my-song' }
        })
      }
    },

    // 获取创作列表
    async getSongList() {
      if (!this.userId) {
        return
      }
      const res = await getUserSongs(this.userId)
      if (res.code === 1) {
        this.songList = res.data
      }
    },
    // 显示上传对话框
    showUploadDialog(isEdit) {
      this.isEdit = isEdit
      this.uploadDialogVisible = true
      if (!isEdit) {
        this.songForm = JSON.parse(JSON.stringify(this.defaultSongForm))
        this.editId = null
        this.$nextTick(() => {
          if (this.$refs.songUpload) {
            this.$refs.songUpload.clearFiles()
          }
          if (this.$refs.picUpload) {
            this.$refs.picUpload.clearFiles()
          }
        })
      }
    },
    // 音频上传成功
    handleSongSuccess(res) {
      if (res.code === 1) {
        this.songForm.url = res.url
        // 预加载音频以验证可用性
        const audio = new Audio(this.attachImageUrl(res.url))
        audio.addEventListener('loadeddata', () => {
          this.$message.success('音频上传成功')
        })
        audio.addEventListener('error', () => {
          this.$message.error('音频文件无法播放')
          this.songForm.url = ''
        })
      }
    },
    // 图片上传成功
    handlePicSuccess(res) {
      if (res.code === 1) {
        this.songForm.pic = res.url
        this.$message.success('封面上传成功')
      } else {
        this.$message.error('封面上传失败')
      }
    },
    // 音频上传前校验
    beforeSongUpload(file) {
      // 添加更详细的音频格式检查
      const audioTypes = ['audio/mpeg', 'audio/mp3', 'audio/wav', 'audio/ogg']
      const isValidType = audioTypes.includes(file.type)
      const isLt20M = file.size / 1024 / 1024 < 20

      console.log('上传音频文件信息:', {
        文件名: file.name,
        文件类型: file.type,
        文件大小: file.size / 1024 / 1024 + 'MB'
      })

      if (!isValidType) {
        this.$message.error(`支持的音频格式: ${audioTypes.join(', ')}`)
        return false
      }
      if (!isLt20M) {
        this.$message.error('音频大小不能超过 20MB!')
        return false
      }
      return true
    },
    // 图片上传前校验
    beforePicUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImage) {
        this.$message.error('请上传图片文件!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    },
    // 提交上传/更新
    async submitUpload() {
      if (!this.songForm.name) {
        this.$message.error('请填写音乐名称')
        return
      }

      const params = {
        ...this.songForm,
        userId: this.userId
      }

      let res
      if (this.isEdit) {
        params.id = this.editId
        res = await updateUserSong(params)
      } else {
        if (!this.songForm.url) {
          this.$message.error('请上传音频文件')
          return
        }
        res = await addUserSong(params)
      }

      if (res.code === 1) {
        this.$message.success(this.isEdit ? '更新成功' : '上传成功')
        this.uploadDialogVisible = false
        this.getSongList()
      }
    },
    // 删除音乐
    async deleteSong(id) {
      this.$confirm('确定删除该音乐?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 如果正在播放这首歌，先停止播放
        if (this.$store.getters.id === id) {
          // 清除播放状态
          this.$store.commit('setIsPlay', false);
          this.$store.commit('setPlayButtonUrl', '#icon-play');
          this.$store.commit('setListOfSongs', []);
          this.$store.commit('setUrl', '');
          this.$store.commit('setId', '');
          this.$store.commit('setTitle', '');
          this.$store.commit('setArtist', '');
          this.$store.commit('setPicUrl', '');
          this.$store.commit('setLyric', []);
        }

        const res = await deleteUserSong(id)
        if (res.code === 1) {
          this.$message.success('删除成功')
          this.getSongList()
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 修改播放音乐方
    playSong(song) {
      // 构造播放器需要的歌曲格式
      const songData = {
        id: song.id,
        name: song.name,
        url: this.attachImageUrl(song.url),
        pic: this.attachImageUrl(song.pic),
        lyric: song.lyric,
        singerId: -1,
        singerName: '我的创作'
      }

      // 更新播放器状态
      this.$store.commit('setCurrentSong', songData);
      this.$store.commit('setPlayList', [songData]);
      this.$store.commit('setListIndex', 0);
      this.$store.commit('setIsPlay', true);

      // 预检查音频是否可播放
      const audio = new Audio(songData.url);
      audio.addEventListener('loadeddata', () => {
        console.log('音频加载成功');
      });
      audio.addEventListener('error', (e) => {
        console.error('音频加载错误:', {
          错误代码: e.target.error.code,
          错误信息: e.target.error.message,
          音频URL: audio.src
        });
        this.$message.error('音频文件无法播放');
      });
    },
    // 修改音频URL处理方法
    attachImageUrl(url) {
      if (!url) return ''
      if (url.startsWith('http')) {
        return url
      }
      return `${this.uploadUrl}${url}`
    },
    // 编辑音乐
    editSong(song) {
      this.editId = song.id
      this.songForm = JSON.parse(JSON.stringify(song))
      this.showUploadDialog(true)
    },
    // 对话框关闭时的处理
    handleDialogClose() {
      this.songForm = JSON.parse(JSON.stringify(this.defaultSongForm))
      this.isEdit = false
      this.editId = null
      if (this.$refs.songUpload) {
        this.$refs.songUpload.clearFiles()
      }
      if (this.$refs.picUpload) {
        this.$refs.picUpload.clearFiles()
      }
    },
    // 获取文件名
    getFileName(url) {
      if (!url) return ''
      return url.split('/').pop()
    }
  }
}
</script>

<style scoped>
.my-song {
  padding: 20px;
}
.song-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.song-pic {
  width: 50px;
  height: 50px;
  border-radius: 5px;
  object-fit: cover;
}
.empty-tip {
  text-align: center;
  color: #909399;
  margin-top: 100px;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader:hover {
  border-color: #FFC0CB;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}
.el-upload__tip {
  color: #606266;
  font-size: 12px;
  margin-top: 7px;
}
</style>